package wechat.controller;

import org.xml.sax.SAXException;
import wechat.core.WechatCore;
import wechat.vo.UserAccessTokenResponse;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by CoderJiang@sina.com on 16-6-28.
 */
public abstract class WechatSupport {

    protected WechatCore weChatCore = new WechatCore();

    protected WechatSupport() throws ParserConfigurationException, SAXException {
    }

    /**
     * 用户初始化
     */
    public void init() {
    }

    public WechatCore getWeChatCore() {
        return weChatCore;
    }

    protected void checkSignature(HttpServletRequest req, HttpServletResponse resp) throws IOException, NoSuchAlgorithmException {
        this.init();
        weChatCore.setReqParams(req.getParameterMap());

        String msg = weChatCore.checkSignature();

        // 输出回复消息
        //resp.setCharacterEncoding("UTF-8");
        //resp.setContentType("text/html");
        resp.getWriter().print(msg);
    }

    public void getUserAccessToken() {
        this.init();
        weChatCore.getUserAccessToken();
    }

    ;

    public String register(String scope, String callbackUrl) {
        this.init();
        return weChatCore.register(scope, callbackUrl);
    }

    ;

    public void handle(ServletInputStream inputStream) throws IOException, SAXException {
        this.weChatCore.handle(inputStream);
    }

    ;

    public UserAccessTokenResponse getUserAccessToken(String code) {
        this.init();
        return this.weChatCore.getUserAccessToken(code);
    }

    ;
}
